import WebSocket from 'ws';
import { wsEvents } from '../src/domain/events/ws.events';
import * as readline from 'readline';

// 创建命令行交互接口
const rl = readline.createInterface({
  input: process.stdin,
  output: process.stdout
});

// 配置
const PORT = process.env.WEBSOCKET_PORT || 8080;
const URL = `ws://localhost:${PORT}`;

// 存储会话信息
let clientId: string | null = null;
let accessToken: string | null = null;
let refreshToken: string | null = null;
let currentUser: any = null;
let currentChatId: string | null = null;

// 创建新WebSocket连接
function createConnection(): Promise<WebSocket> {
  return new Promise((resolve, reject) => {
    const ws = new WebSocket(URL);

    ws.on('open', () => {
      console.log('已连接到服务器');
      resolve(ws);
    });

    ws.on('error', (error) => {
      console.error('连接错误:', error.message);
      reject(error);
    });

    // 设置消息处理器
    ws.on('message', (data) => {
      try {
        const message = JSON.parse(data.toString());
        handleServerMessage(ws, message);
      } catch (error: any) {
        console.error('消息解析错误:', error.message);
      }
    });

    ws.on('close', () => {
      console.log('与服务器的连接已关闭');
    });
  });
}

// 处理来自服务器的消息
function handleServerMessage(ws: WebSocket, message: any) {
  const { type, payload } = message;

  console.log(`\n收到服务器消息: ${type}`);

  switch (type) {
    case wsEvents.CONNECT:
      clientId = payload.clientId;
      console.log(`已分配客户端ID: ${clientId}`);
      showMainMenu(ws);
      break;

    case wsEvents.AUTH_SUCCESS:
      console.log('认证成功!');
      currentUser = payload.user;
      accessToken = payload.accessToken || null;
      refreshToken = payload.refreshToken || null;
      console.log(`用户信息: 
  ID: ${currentUser.id}
  用户名: ${currentUser.username}
  角色: ${currentUser.role}
  状态: ${currentUser.status}`);
      if (accessToken) {
        console.log(`访问令牌: ${accessToken.substring(0, 20)}...`);
      }
      showAuthenticatedMenu(ws);
      break;

    case wsEvents.AUTH_FAILURE:
      console.log(`认证失败: ${payload.error}`);
      showMainMenu(ws);
      break;

    case wsEvents.REGISTER_SUCCESS:
      console.log('注册成功!');
      console.log(`新用户信息: 
  ID: ${payload.user.id}
  用户名: ${payload.user.username}
  角色: ${payload.user.role}`);
      showMainMenu(ws);
      break;

    case wsEvents.REGISTER_FAILURE:
      console.log(`注册失败: ${payload.error}`);
      showMainMenu(ws);
      break;

    case wsEvents.CHAT_HISTORY:
      console.log(`接收到聊天历史记录, 聊天ID: ${payload.chatId}`);
      console.log(`消息数量: ${payload.messages.length}`);
      currentChatId = payload.chatId;
      
      if (payload.messages.length > 0) {
        console.log('历史消息:');
        payload.messages.forEach((msg: any) => {
          console.log(`${msg.sender} (${new Date(msg.time).toLocaleTimeString()}): ${msg.content}`);
        });
      } else {
        console.log('没有历史消息');
      }
      
      showChatMenu(ws);
      break;

    case wsEvents.NEW_MESSAGE:
      console.log(`\n新消息 (${payload.message.sender}): ${payload.message.content}`);
      break;

    case wsEvents.MESSAGE_DELIVERED:
    case wsEvents.MESSAGE_RECEIVED:
    case wsEvents.MESSAGE_ANALYZING:
    case wsEvents.MESSAGE_COMPLETED:
      console.log(`消息状态: ${type} - ${payload.status || ''} ${payload.statusText || ''}`);
      break;

    case wsEvents.ERROR:
      console.log(`错误: ${payload.error}`);
      break;

    default:
      console.log('收到其他类型消息:', message);
  }
}

// 显示主菜单
function showMainMenu(ws: WebSocket) {
  console.log('\n=== 主菜单 ===');
  console.log('1. 注册新用户');
  console.log('2. 使用用户名密码登录');
  console.log('3. 使用令牌登录 (如果有)');
  console.log('4. 退出');

  rl.question('请选择操作: ', (answer) => {
    switch (answer) {
      case '1':
        registerUser(ws);
        break;
      case '2':
        loginWithCredentials(ws);
        break;
      case '3':
        loginWithToken(ws);
        break;
      case '4':
        ws.close();
        rl.close();
        console.log('测试已结束');
        break;
      default:
        console.log('无效选择，请重试');
        showMainMenu(ws);
    }
  });
}

// 显示已认证菜单
function showAuthenticatedMenu(ws: WebSocket) {
  console.log('\n=== 已认证菜单 ===');
  console.log('1. 创建/加入聊天会话');
  console.log('2. 查看用户信息');
  console.log('3. 注销');
  console.log('4. 退出');

  rl.question('请选择操作: ', (answer) => {
    switch (answer) {
      case '1':
        joinChat(ws);
        break;
      case '2':
        showUserInfo();
        showAuthenticatedMenu(ws);
        break;
      case '3':
        logout();
        showMainMenu(ws);
        break;
      case '4':
        ws.close();
        rl.close();
        console.log('测试已结束');
        break;
      default:
        console.log('无效选择，请重试');
        showAuthenticatedMenu(ws);
    }
  });
}

// 显示聊天菜单
function showChatMenu(ws: WebSocket) {
  console.log('\n=== 聊天菜单 ===');
  console.log('1. 发送消息');
  console.log('2. 发送正在输入通知');
  console.log('3. 返回主菜单');
  console.log('4. 退出');

  rl.question('请选择操作: ', (answer) => {
    switch (answer) {
      case '1':
        sendMessage(ws);
        break;
      case '2':
        toggleTyping(ws);
        break;
      case '3':
        showAuthenticatedMenu(ws);
        break;
      case '4':
        ws.close();
        rl.close();
        console.log('测试已结束');
        break;
      default:
        console.log('无效选择，请重试');
        showChatMenu(ws);
    }
  });
}

// 注册新用户
function registerUser(ws: WebSocket) {
  rl.question('请输入用户名: ', (username) => {
    rl.question('请输入密码: ', (password) => {
      rl.question('请输入邮箱 (可选): ', (email) => {
        const registerMsg = {
          type: wsEvents.REGISTER_REQUEST,
          payload: {
            username,
            password,
            email: email || undefined
          }
        };
        
        ws.send(JSON.stringify(registerMsg));
      });
    });
  });
}

// 使用用户名密码登录
function loginWithCredentials(ws: WebSocket) {
  rl.question('请输入用户名: ', (username) => {
    rl.question('请输入密码: ', (password) => {
      const loginMsg = {
        type: wsEvents.AUTH_REQUEST,
        payload: {
          username,
          password
        }
      };
      
      ws.send(JSON.stringify(loginMsg));
    });
  });
}

// 使用令牌登录
function loginWithToken(ws: WebSocket) {
  if (!accessToken) {
    console.log('没有可用的访问令牌');
    showMainMenu(ws);
    return;
  }

  const tokenMsg = {
    type: wsEvents.AUTH_REQUEST,
    payload: {
      token: accessToken
    }
  };
  
  ws.send(JSON.stringify(tokenMsg));
}

// 加入聊天会话
function joinChat(ws: WebSocket) {
  rl.question('请输入聊天ID (留空创建新会话): ', (chatId) => {
    const joinChatMsg = {
      type: wsEvents.JOIN_CHAT,
      payload: {
        chatId: chatId || undefined
      }
    };
    
    ws.send(JSON.stringify(joinChatMsg));
  });
}

// 发送消息
function sendMessage(ws: WebSocket) {
  if (!currentChatId) {
    console.log('未加入任何聊天会话');
    showAuthenticatedMenu(ws);
    return;
  }

  rl.question('请输入消息内容: ', (content) => {
    const messageId = `msg-${Date.now()}`;
    const sendMessageMsg = {
      type: wsEvents.SEND_MESSAGE,
      payload: {
        chatId: currentChatId,
        message: {
          id: messageId,
          content,
          sender: currentUser.id
        }
      }
    };
    
    ws.send(JSON.stringify(sendMessageMsg));
    
    // 消息发送后自动返回聊天菜单
    setTimeout(() => {
      showChatMenu(ws);
    }, 500);
  });
}

// 发送正在输入通知
function toggleTyping(ws: WebSocket) {
  if (!currentChatId) {
    console.log('未加入任何聊天会话');
    showAuthenticatedMenu(ws);
    return;
  }

  rl.question('输入状态 (1: 开始输入, 0: 停止输入): ', (status) => {
    const isTyping = status === '1';
    
    const typingMsg = {
      type: wsEvents.TYPING,
      payload: {
        chatId: currentChatId,
        isTyping
      }
    };
    
    ws.send(JSON.stringify(typingMsg));
    console.log(`已发送${isTyping ? '开始' : '停止'}输入通知`);
    showChatMenu(ws);
  });
}

// 显示用户信息
function showUserInfo() {
  if (!currentUser) {
    console.log('未登录');
    return;
  }

  console.log('\n=== 用户信息 ===');
  console.log(`ID: ${currentUser.id}`);
  console.log(`用户名: ${currentUser.username}`);
  console.log(`邮箱: ${currentUser.email || '未设置'}`);
  console.log(`角色: ${currentUser.role}`);
  console.log(`状态: ${currentUser.status}`);
  
  if (accessToken) {
    console.log(`访问令牌: ${accessToken.substring(0, 20)}...`);
  }
  
  if (refreshToken) {
    console.log(`刷新令牌: ${refreshToken.substring(0, 20)}...`);
  }
}

// 注销
function logout() {
  clientId = null;
  accessToken = null;
  refreshToken = null;
  currentUser = null;
  currentChatId = null;
  console.log('已注销');
}

// 主函数
async function main() {
  try {
    console.log('正在连接到 WebSocket 服务器...');
    const ws = await createConnection();
    
    // 处理程序终止
    process.on('SIGINT', () => {
      console.log('\n正在断开连接...');
      ws.close();
      rl.close();
      process.exit(0);
    });
    
  } catch (error: any) {
    console.error('启动失败:', error.message);
    rl.close();
  }
}

// 运行测试
main().catch(console.error); 